<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/7/13
 * Time: 14:10:06
 */

namespace Service\DecorateService;

use Service\ActivityService\ActivityStoreService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Layout;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\LayoutStore;
use Service\ActivityService\MnActivityService;
use Service\ActivityService\ActivityService;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\StoreActivity;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\Activity;
use App\Model\BbcModel\GoodsGroup;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsGroupList;
use Service\GoodsService\MnGoodsService;

class DecorateService extends BaseService
{

    public $_tab_router_path = "Service\\LayoutService\\";

    /*需要处理的组件*/
    public $module = [
        'newImageAd',
        'imageTextNav',
        'cube',
        'goodsGroup',
        'subject',
        'titleText',
        'video',
        'brandGroup',

    ];

    /*跳转链接*/
    public $link_type = [
        'basic'             => 1,   //基础页面
        'microPage'         => 2,   //微页面
        'ordinaryGoods'     => 3,   //普通商品
        'subjectList'       => 4,   //专题列表
        'seckillGoods'      => 5,   //秒杀商品
        'groupBookingGoods' => 6,   //拼团商品
        'classify'          => 7,   //商品分类
        'seckillList'       => 8,   //秒杀
        'groupBookingList'  => 9,   //拼团
        'moneyOff'          => 10,  //满减
        'customLink'        => 11,  //自定义链接
        'brand'             => 12   //品牌
    ];

    public function Decorate($param){
        if(!isset($param['cid']) || !$param['cid']){
            return Normal::returnCode(Normal::FAIL,'缺少渠道ID');
        }
        $is_preview = $param['isPreview'] ?? 0;
        $mn_user = Mnuser::instance()->where(['id'=>$param['mn_sid']])->first();
        if($is_preview == 1){ //预览
            $result = $this->preview($param);
            if($result['code'] != Normal::SUC){
                return Normal::returnCode(Normal::FAIL,$result['msg']);
            }
            $decorate = $result['data'];
        }else{
            if(!isset($param['mn_sid']) || !$param['mn_sid']){
                return ['status'=>Normal::FAIL,'msg'=>'缺少店铺ID'];
            }

            if(isset($param['decorate_id']) && $param['decorate_id']){ //获取Tab页关联的指定微页面
                //店铺自定义的装修数据
                $decorate = LayoutStore::instance()
                    ->where(['mn_sid'=>$param['mn_sid'],'layout_id'=>$param['decorate_id'],'type'=>1,'is_tab'=>0,'df'=>0])
                    ->select(['name','image','content','is_tab','layout_ids'])
                    ->first();
                if(!$decorate){ //店铺未自定义装修内容，获取渠道的装修内容
                    $decorate = Layout::instance()->where(['id'=>$param['decorate_id'],'is_tab'=>0])
                        ->select(['name','image','content','is_tab','layout_ids'])
                        ->first();
                }
            }else{ //获取店铺的首页（首页是微页面）

                //店铺自定义的装修数据
                $decorate = LayoutStore::instance()
                    ->where(['mn_sid'=>$param['mn_sid'],'layout_id'=>$mn_user['layout_id'],'type'=>1,'is_tab'=>0,'df'=>0])
                    ->select(['name','image','content','is_tab','layout_ids'])
                    ->first();
                if(!$decorate){//店铺未自定义装修内容，获取渠道的装修内容
                    $decorate = Layout::instance()->where(['id'=>$mn_user['layout_id'],'is_tab'=>0])
                        ->select(['name','image','content','is_tab','layout_ids'])
                        ->first();
                }
            }
            $decorate['is_show_goods_list'] = Layout::instance()
                                                  ->where(['id'=>$mn_user['layout_id']])
                                                  ->first()->toArray()['is_show_goods_list'] ?? 1;
        }

        if(!isset($decorate['content'])){ //店铺没有设置微页面 或 微页面没有装修数据
            $decorate['name'] = '默认页面';
            $decorate['image'] = '';
            $decorate['content'] = $this->defaultLayout(0,$param['cid']);
        }

        $decorate['content'] = json_decode($decorate['content'],true);
        $content = $decorate['content']['content'];

        $mnid   = (int)$param['mnid'] ?? 0;
        $cid    = (int)$param['cid'] ?? 0;
        $mn_sid = (int)$param['mn_sid'] ?? 0;
        $mid    = (int)$param['mid'] ?? 0;
        if(!is_array($mn_user)){ //有些方法定义了参数类型。所以转换为数组格式
            $mn_user = $mn_user->toArray();
        }

        //店铺最近一场拼团和秒杀活动及活动商品
        $storeActivity = ActivityStoreService::instance()->getStoreSpecialActivity($cid,$mn_sid,$mid);

        //查询特价活动
        $mn_user_activity_goods = MnActivityService::instance()->getActivityGoodsList($mn_sid);

        $moduleData = [];
        foreach ($content as $value){
            if(in_array($value['type'],['newImageAd','cube','imageTextNav'])){ //图片广告,魔方,图文导航用同一个方法处理数据
                $router_path = $this->_tab_router_path . 'newImageAd';
                if( !class_exists($router_path) ) {
                    continue;
                }
                if( !method_exists($router_path,'getDataList') ) {
                    continue;
                }
                $_router_data = $router_path::instance()->getDataList($mnid,$cid,$mn_user,$mid,$value,[
                    'mn_user_activity_goods'    => $mn_user_activity_goods ?? [],
                    'storeActivity'             => $storeActivity ?? [],
                ]);
                if($_router_data){
                    $moduleData[] = $_router_data;
                }
            }else if(in_array($value['type'],$this->module)){
                $router_path = $this->_tab_router_path . $value['type'];
                if( !class_exists($router_path) ) {
                    continue;
                }
                if( !method_exists($router_path,'getDataList') ) {
                    continue;
                }
                $_router_data = $router_path::instance()->getDataList($mnid,$cid,$mn_user,$mid,$value,[
                    'mn_user_activity_goods'    => $mn_user_activity_goods ?? [],
                    'storeActivity'             => $storeActivity??[],
                ]);
                if($_router_data){
                    $moduleData[] = $_router_data;
                }
            }else{
                $moduleData[] = $value;
            }
        }
        if(!is_array($decorate)){
            $returnData = $decorate->toArray();
        }else{
            $returnData = $decorate;
        }
        $returnData['content']['content'] = $moduleData;
        return Normal::returnCode(Normal::SUC,'请求成功',$returnData);
    }

    public function preview($param){
        $param['is_formal'] = $param['is_formal'] ?? 0;//0-预览草稿，1-预览正式
        if(!isset($param['previewID'])){
            return Normal::returnCode(Normal::FAIL,'缺少预览模板ID');
        }
        if($param['is_formal'] == 1){
            $field = ['name','image','content','is_tab','layout_ids'];
        }else{
            $field = ['name','image','draft_content as content','is_tab','layout_ids','is_show_goods_list'];
        }
        $decorate = Layout::instance()
            ->where([
                ['id','=',$param['previewID']],
            ])
            ->select($field)
            ->get()->toArray();
        return Normal::returnCode(Normal::SUC,'请求成功',$decorate);
    }

    /**
     * 默认微页面数据
     * @param $is_add,0-初始化数据新增数据，1-只是显示用
     * @param $cid
     * @return string
     */
    public function defaultLayout($is_add = 0,$cid){
        $content = '{"config":{"show_method":0,"bgColor":"#f9f9f9","bgImg":"","uuid":"8ecb0247-5d0e-4313-8a46-a80ca267b7d2"},"navigationbar_config":{"navigationbar_config_type":"global","title":"店铺首页","logo":"","search":"1","placeholder":"搜索商品","bg_color":"#f2f2f2","color":"#333","search_switch":"1","navigationbar_type":"standard","search_color":"#ffffff","uuid":"9c6e42af-6b20-4cc6-afaf-88532b14f219"},"content":[{"type":"newImageAd","title":"图片广告  ","component":"newImageAd","style":"newImageAdStyle","maxNum":500,"status":true,"setStyle":{"show_method":1,"swipe_time":3000,"indicator":1,"indicator_algin":"center","count":1,"bg_color":"#ffffff","com_color":"#ffffff","select_bg":"#D24667","top_margin":0,"bottom_margin":0,"page_margin":0,"img_margin":0,"overlap_height":0,"top_radius":0,"bottom_radius":0,"sub_entry":[{"title":"","link_type":"","link_id":"","link_title":"","image_url":"https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/decorate/baa30c4d-10c0-4307-a49e-d006de4ea16e_WechatIMG1898.jpeg"},{"title":"","link_type":"","link_id":"","link_title":"","image_url":"https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/decorate/90b17e7e-467f-499a-afee-2fc42b04d3c0_WechatIMG1907.jpeg"},{"title":"","link_type":"","link_id":"","link_title":"","image_url":"https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/decorate/b63bcf6e-5e9b-4d3b-9ad3-060fc1ac4d81_WechatIMG1906.jpeg"}],"topRadius":0,"bottomRadius":0},"uuid":"7ed75c53-ba24-4cdc-b534-d900d4e3b99b"}]}';

        if($is_add){
            $insertData['sid']        = getSID();
            $insertData['cid']        = $cid;
            $insertData['type']       = 1;
            $insertData['name']       = '默认页面';
            $insertData['content']    = $content;
            $insertData['is_release'] = 1;
            $insertData['is_default'] = 1;
            $insertData['cd']         = time();
            $insertData['md']         = time();

            Layout::instance()
                ->insert($insertData);
        }
        return $content;
    }

    /**
     * 获取一场秒杀或拼团
     * @param $param
     * @return array|void
     */
    public function lastActivity($param){
        ActivityService::instance()->updateActivityStatusDown();

        if(!isset($param['type']) || !$param['type']){
            return Normal::returnCode(Normal::FAIL,'缺少活动类型');
        }

        $cid    = (int)$param['cid'];
        $mn_sid = (int)$param['mn_sid'];
        $mid    = (int)$param['mid'];

        $config_channel = ConfigChannel::instance()
            ->where([
                ['code','=','shopping_vip_type'],
                ['cid','=',$cid],
            ])
            ->first();

        if(isset($param['activity_id']) && $param['activity_id']) { //指定活动
            $activity = $this->activityInfo($cid,$mn_sid,$mid,$param['activity_id'],$param['type'],$config_channel);
        }else{
            $res = ActivityStoreService::instance()->getStoreSpecialActivity($cid,$mn_sid,$mid,$config_channel);
            if($param['type'] == 3){
                $activity = $res['seckillActivity'];
            }else{
                $activity = $res['bookActivity'];
            }
            if(isset($activity['goods']) && (count($activity['goods']) <= 0)){
                $activity = null;
            }
            if(isset($activity['goods']) && (count($activity['goods']) > 0)){
                $activity['goods_list'] = $activity['goods'];
                unset($activity['goods']);
            }
        }

        if(is_array($activity) && count($activity) <= 0){
            $activity = null;
        }else if(!$activity){
            $activity = null;
        }
        $settingPrice = ConfigChannel::instance()->getPriceSet(['cid'=>$param['cid']]);

        if(isset($activity['goods_list']) && !empty($activity['goods_list'])){
            $goods_list = $activity['goods_list'];
            foreach ($goods_list as &$v){
                if($settingPrice==0){
                    if($v['is_bonded']==1 && $v['tax_free']==0){
                        $v['price_recommend'] = upDecimal($v['price_recommend'] + $v['price_recommend'] * $v['tax_rate'],1);
                    }else{
                        $v['price_recommend'] = upDecimal($v['price_recommend'],1);
                    }
                }else{
                    if($v['is_bonded']==1 && $v['tax_free']==0){
                        $v['price_recommend'] = ceil($v['price_recommend'] + $v['price_recommend'] * $v['tax_rate']);
                    }else{
                        $v['price_recommend'] = ceil($v['price_recommend']);
                    }
                }
            }
            $activity['goods_list'] = $goods_list;
        }

        return Normal::returnCode(Normal::SUC,'请求成功',$activity);
    }

    /**
     * 根据活动ID获取活动详情及活动商品列表
     * @param $cid
     * @param $mn_sid
     * @param $mid
     * @param $activity_id
     * @param $activity_type
     */
    public function activityInfo($cid,$mn_sid,$mid,$activity_id,$activity_type,$config_channel){
        $store_activity_status = StoreActivity::instance()
            ->where([
                ['mn_sid','=',$mn_sid],
                ['activity_id','=',$activity_id],
            ])
            ->value('id');
        if($store_activity_status){ //活动被店铺禁用
            return null;
        }
        $storeActivity = Activity::instance()
            ->leftJoin('ly_activity_store','ly_activity_store.activity_id','=','ly_activity.id')
            ->where([
                ['ly_activity.id','=',$activity_id],
                ['ly_activity.df','=',0],
                ['ly_activity.cid','=',$cid],
            ])
            ->whereIn('ly_activity.status',[0,1])
            ->where(function ($query) use ($mn_sid){
                $query->where('ly_activity_store.mn_sid',$mn_sid)
                    ->orWhere('ly_activity_store.mn_sid',0);
            })
            ->where(function ($query) use ($config_channel){
                if(!empty($config_channel)){
                    $vip_type = json_decode($config_channel['value'],true);
                    if($vip_type['vip_type'] == 1){ //非会员模式
                        $query->where('ly_activity.target_type','<>',3);
                    }

                }
            })
            ->select([
                'ly_activity.id',
                'ly_activity.name',
                'ly_activity.begindate',
                'ly_activity.enddate',
                'ly_activity.begintime',
                'ly_activity.endtime',
                'ly_activity.type',
                'ly_activity.target_type'
            ])
            ->first();
        if(!$storeActivity){
            return null;
        }
        $storeActivity = $storeActivity->toArray();
        $res = ActivityStoreService::instance()->activityGoodsList($cid,$mn_sid,$mid,[$storeActivity],0,7,['type'=>$activity_type]);
        if(!$res){
            return null;
        }
        $param['activity'] = $storeActivity;
        $param['time_start_str'] = strtotime($storeActivity['begintime']);
        $param['time_end_str'] = strtotime($storeActivity['endtime']);
        $param['time'] = time();
        $activity_info = ActivityStoreService::instance()->checkActivityTime($param);

        $returnData = $activity_info;
        $returnData['goods_list'] = $res;

        return $returnData;
    }

    public function lastSpecActivity($param){
        $cid    = (int)$param['cid'];
        $mn_sid = (int)$param['mn_sid'];
        $mid    = (int)$param['mid'];

        $mn_user = Mnuser::instance()->where(['id'=>$mn_sid])->first()->toArray();
        $mn_user_activity_goods = ActivityStoreService::instance()->getMnSpecialActivityGoodsList($cid, $mn_sid,$mn_user);
        $return = null;
        if(isset($mn_user_activity_goods['special_activity'])){
            $return['activity_id'] = $mn_user_activity_goods['special_activity']['id'];
            $return['name']        = $mn_user_activity_goods['special_activity']['name'];
            $return['type']        = $mn_user_activity_goods['special_activity']['type'];


            $startdate   = $mn_user_activity_goods['special_activity']['startdate'];
            $enddate     = $mn_user_activity_goods['special_activity']['enddate'];

            if($startdate < time()){ //已开始
                $return['start'] = 1;
                $return['countdown'] = $enddate - time();
            }else{
                $return['start'] = 0;
                $return['countdown'] =  $startdate-time();
            }
            $return['goods_list']  = $mn_user_activity_goods['special_activity_goods'];
        }
        return Normal::returnCode(Normal::SUC,'请求成功',$return);
    }

    public function groupGoodslist($param){
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;

        if(!isset($param['group_id']) || !$param['group_id']){
            return Normal::returnCode(Normal::FAIL,'缺少商品分组ID',[]);
        }

        $goods_group = GoodsGroup::instance()
            ->where(['id'=>$param['group_id'],'df'=>0,'status'=>1,'cid'=>$param['cid']])
            ->first();
        if(!$goods_group){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在',[]);
        }

        if($goods_group['goods_range'] == 1){ //全部商品
            $goods_ids = Goods::instance()
                ->where(['sid'=>config('STORE_ID'),'cid'=>$param['cid'],'df'=>0,'status'=>1])
                ->pluck('id')->toArray();
        }else{
            $goods_ids = GoodsGroupList::instance()
                ->where(['goods_group_id'=>$goods_group['id'],'df'=>0])
                ->pluck('goods_id')->toArray();
            if(!$goods_ids){
                return Normal::returnCode(Normal::FAIL,'商品分组没有商品',[]);
            }
        }

        $mn_user = Mnuser::instance()->where(['id'=>$param['mn_sid']])->first()->toArray();

        $goods_list = Goods::instance()
            ->leftJoin('ly_mn_store_goods',"ly_mn_store_goods.goods_id","=","ly_goods.id")
/*            ->leftJoin('ly_goods_batch',"ly_goods_batch.goods_id", "=", "ly_goods.id AND ly_goods_batch.df = 0 AND IF(ly_goods.is_trade = 1,ly_goods_batch.mn_sid = $param[mn_sid] AND ly_goods_batch.type = 1,ly_goods_batch.type = 0)")*/
            ->whereIn('ly_goods.id',$goods_ids)
            ->where('ly_goods.status',1)
            ->where('ly_goods.df',0)
            ->where('ly_mn_store_goods.mn_sid',$param['mn_sid'])
            ->where('ly_mn_store_goods.status',1)
            ->where(function ($query) use ($mn_user){
                if($mn_user['type'] == 2){
                    $query->selectRaw(Db::raw("((ly_goods.status=1 and ly_goods.df=0 and ly_goods.is_trade=0) or (ly_goods.is_trade=1 and (ly_mn_store_goods.df=0 or (ly_mn_store_goods.df=1 and ly_mn_store_goods.num>0) or (ly_mn_store_goods.pre_sell=1 and ly_mn_store_goods.pre_storage>0))))"));
                }else{
                    $query->selectRaw(Db::raw("ly_goods.is_trade=0"));
                }
            })
            ->where(function ($query) use ($mn_user){
                if($mn_user['type']==3){
                    switch ($mn_user['goods_source']){
                        case 1://只卖普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=0)"));
                            break;
                        case 2://只卖前置仓
                            $query->selectRaw(Db::raw("(ly_goods.supplier_id=$mn_user[supplier_id])"));
                            break;
                        case 3://前置仓+普通仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=0))"));
                            break;
                        case 4://只卖中心仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=2)"));
                            break;
                        case 5://中心仓+普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery<>1)"));
                            break;
                        case 6://中心仓+前置仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=2))"));
                            break;
                        case 7://所有仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery in (0,2)))"));
                            break;
                    }
                }else{
                    $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery <> 1)"));
                }
            })
            ->orderByRaw('ly_mn_store_goods.show_order desc,ly_goods.id desc')
            ->paginate($limit, ['ly_goods.id'], 'page', $page);

        $total = $goods_list->total();
        $goods_list = $goods_list->items();

        $goods_ids = array_column($goods_list,'id');

        $cid    = (int)$param['cid'];
        $mnid   = (int)$param['mnid'];
        $mid    = (int)$param['mid'];
        $mn_sid = (int)$param['mn_sid'];

        //查询特价活动
        $aWhere = [
            ['ly_mn_activity.mn_sid', '=', $param['mn_sid']],
            ['ly_mn_activity.status', '=', 1],
            ['ly_mn_activity.startdate', '<', time()],
            ['ly_mn_activity.enddate', '>', time()],
        ];
        $special_activity_goodslist = Db::table('ly_mn_activity')
            ->leftJoin('ly_mn_activity_goods','ly_mn_activity_goods.mn_activity_id','=','ly_mn_activity.id')
            ->where($aWhere)
            ->where(['ly_mn_activity_goods.df'=>0])
            ->select(explode(',','ly_mn_activity.id,ly_mn_activity.type,ly_mn_activity.name,ly_mn_activity.full,ly_mn_activity.drop,ly_mn_activity_goods.price,ly_mn_activity_goods.goods_id'))
            ->get()->toArray();
        $goods_list    = MnGoodsService::instance()->goodsListFormat($cid,$mn_sid,$mid,$goods_ids,1,$mn_user,$special_activity_goodslist);

        return Normal::returnCode(Normal::SUC,'成功',['list'=>$goods_list,'total'=>$total]);
    }
}